package earogya.pharmacy.pharmacy.messages;

import java.io.IOException;
import java.sql.Time;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.datatype.EI;
import ca.uhn.hl7v2.model.v251.message.RDE_O11;
import ca.uhn.hl7v2.model.v251.segment.ORC;
import ca.uhn.hl7v2.model.v251.segment.RXO;
import earogya.pharmacy.pharmacy.OrderDrugs;
import earogya.pharmacy.pharmacy.PharmacyHibernateManager;

/*Class RDE_O11_Order
 * 
 * orders drugs to the pharmacy
 * 
 * */
public class RDE_O11_Order {

	private RDE_O11 adrMsg;
	private PharmacyHibernateManager hibernate_manager = new PharmacyHibernateManager();
	private OrderDrugs order = new OrderDrugs();

	public RDE_O11_Order(RDE_O11 adrMsg) {
		this.adrMsg = adrMsg;
	}

	public String manageMessage() throws HL7Exception, IOException {
		String ack = null;
		try {
			ack = adrMsg.generateACK().encode();
			this.updateOrderDetails();
		} catch (HL7Exception e) {
			ack = adrMsg.generateACK("OE", e).encode();
		}
		return ack;
	}

	public void updateOrderDetails() throws DataTypeException {
		RXO rxo = adrMsg.getORDER().getORDER_DETAIL().getRXO();
		ORC orc = adrMsg.getORDER().getORC();
		EI rId = orc.getOrc2_PlacerOrderNumber();
		order.setOrderId(Integer.parseInt(rId.getEi1_EntityIdentifier()
				.getValue()));

		if (orc.getOrc7_QuantityTiming(0).getQuantity().getCq1_Quantity()
				.getValue() == null) {
		} else {
			order.setQuantity(Integer.parseInt(orc.getOrc7_QuantityTiming(0)
					.getQuantity().getCq1_Quantity().getValue()));
		}
		if (orc.getDateTimeOfTransaction().getTime().getValueAsDate() == null) {
		} else {
			order.setOrderDate(orc.getDateTimeOfTransaction().getTime()
					.getValueAsDate());
			order.setOrderTime(this.toTime());
		}

		if (rxo.getRxo1_RequestedGiveCode().getIdentifier().getValue() == null) {
		} else {
			order.setDrugId(Integer.parseInt(rxo.getRxo1_RequestedGiveCode()
					.getIdentifier().getValue()));
		}
		hibernate_manager.saveObject(order);
	}

	@SuppressWarnings("deprecation")
	public Time toTime() throws DataTypeException {
		int hh = 0, mm = 0, ss = 0;
		ORC orc = adrMsg.getORDER().getORC();
		try {
			hh = orc.getDateTimeOfTransaction().getTime().getHour();
			mm = orc.getDateTimeOfTransaction().getTime().getMinute();
			ss = orc.getDateTimeOfTransaction().getTime().getSecond();
		} catch (DataTypeException e) {
		}
		Time time = new Time(hh, mm, ss);
		return time;

	}
}
